package com.thoughtworks.wechatmoments.logic.moments;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.thoughtworks.wechatmoments.R;
import com.thoughtworks.wechatmoments.Config;
import com.thoughtworks.wechatmoments.entity.TweetsEntity;
import com.thoughtworks.wechatmoments.entity.UserInfoEntity;

import java.util.List;

/**
 * desc   : 微信朋友圈页面
 * author : guowenlong
 * Email  : guowenlong20000@gmail.com
 */
public class MomentsActivity extends AppCompatActivity implements MomentsContract.View {
    private MomentsRecycleViewAdapter mMomentsAdapter;
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private int mIndex = Config.TWEETS_INDEX;
    private MomentsPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        initData();
    }


    private void initView() {
        mPresenter = new MomentsPresenter();
        mPresenter.attachView(this);
        mRecyclerView = findViewById(R.id.rv_tweets);
        mRefreshLayout = findViewById(R.id.srl_refreshLayout);
    }

    private void initListener() {
        mRefreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.getUserTweets());
        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> mPresenter.getMoreTweets(mIndex, Config.TWEETS_LIMIT));
        mMomentsAdapter = new MomentsRecycleViewAdapter();
        mRecyclerView.setAdapter(mMomentsAdapter);
    }

    private void initData() {
        mPresenter.getUserTweetsOneTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getUserInfo();
    }

    @Override
    public void showUserInfo(UserInfoEntity bean) {
        mMomentsAdapter.setUserInfo(bean);
        mMomentsAdapter.notifyDataSetChanged();
    }

    @Override
    public void showTweets(List<TweetsEntity> tweets) {
        mIndex = tweets.size();
        mMomentsAdapter.refreshTweets(tweets);
        mMomentsAdapter.notifyDataSetChanged();
        if (mRefreshLayout != null) mRefreshLayout.finishRefresh(2000);
    }

    @Override
    public void showMoreTweets(List<TweetsEntity> tweets) {
        mIndex += tweets.size();
        mMomentsAdapter.addTweetsList(tweets);
        mMomentsAdapter.notifyDataSetChanged();
        if (mRefreshLayout != null) mRefreshLayout.finishLoadMore(2000);
    }
}